package controllers

import (
	"strconv"
	"xiegao/models"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type Banner struct {
	beego.Controller
}

// @Title Banner
// @Description 获取全部Banner
// @Success 200 {object} models.banner.Banner
// @Params sort query string false 排序
// @Param   page     query   int false       "当前页"
// @Param   limit    query   int false       "提取条数"
// @router /banner [get]
func (self *Banner) List() {
	limit, _ := self.GetInt("limit")
	page, _ := self.GetInt("page")
	o := orm.NewOrm()
	defer o.Commit()
	var result []models.Banner
	_, error := o.QueryTable("banner").OrderBy("sort").Offset(limit * (page - 1)).Offset(limit * page).All(&result)
	if error != nil {
		self.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "获取失败",
		}
		self.ServeJSON()
		self.StopRun()
	}
	self.Data["json"] = map[string]interface{}{
		"code": 200,
		"data": result,
		"msg":  "获取成功",
	}
	self.ServeJSON()
	self.StopRun()
}

// @Title 添加Banner
// @description 添加Banner
// @Params Description body string  描述
// @Params Image body string  图片地址
// @Params Linker body string  链接
// @Params Sort body int  排序
// @Success 200 {object} models.banner.Banner
// @router /banner [post]
func (self *Banner) AddOne() {
	description := self.GetString("Description")
	image := self.GetString("Image")
	linker := self.GetString("Linker")
	sort, _ := self.GetInt("Sort")
	banner := &models.Banner{
		Description: description,
		Image:       image,
		Linker:      linker,
		Sort:        sort,
	}
	o := orm.NewOrm()
	o.Insert(banner)
	self.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "新建成功",
		"data": banner,
	}
	self.ServeJSON()
	self.StopRun()
}

// @Title 删除Banner
// @description 删除Banner
// @Params id path int  BannerId
// @Success 200 {"code": 200,"msg":"删除成功"}
// @router /banner/:id [delete]
func (self *Banner) DeleteOne() {
	id := self.Ctx.Input.Param(":id")
	BannerId, _ := strconv.Atoi(id)
	banner := &models.Banner{Id: BannerId}

	o := orm.NewOrm()
	defer o.Commit()
	_, error := o.Delete(banner)
	if error != nil {
		self.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "删除失败",
		}
		self.ServeJSON()
		self.StopRun()
	}

	self.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "删除成功",
	}
	self.ServeJSON()
	self.StopRun()

}

// @Title 获取一个Banner
// @description 获取获一个Banner
// @Params id path int  BannerId
// @Success 200 {"code": 200,"msg":"获取成功"}
// @router /banner/:id [get]
func (self *Banner) GetOne() {
	id := self.Ctx.Input.Param(":id")
	BannerId, _ := strconv.Atoi(id)
	banner := &models.Banner{}

	o := orm.NewOrm()
	error := o.QueryTable("banner").Filter("id", BannerId).One(banner)
	if error != nil {
		self.Data["json"] = map[string]interface{}{
			"code": 404,
			"msg":  "无结果",
		}
		self.ServeJSON()
		self.StopRun()
	}

	self.Data["json"] = map[string]interface{}{
		"code": 200,
		"data": banner,
		"msg":  "获取成功",
	}
	self.ServeJSON()
	self.StopRun()

}
